<!--  -->
<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>属性管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区 -->
    <el-card>
      <el-row :gutter="24">
        <el-col :span="24">
          <div class="mod-config">
          <el-form :inline="true" :model="dataForm" @keyup.enter.native="getAttrList()">
            <el-form-item>
              <el-input v-model="dataForm.key" placeholder="参数名" clearable></el-input>
            </el-form-item>
            <el-form-item>
              <el-button @click="getAttrList()">属性查询</el-button>
              <el-button type="primary" @click="addOrUpdateHandle()">新增属性分组</el-button>
              <el-button  type="danger" @click="deleteHandle()" :disabled="dataListSelections.length <= 0">批量删除</el-button>
            </el-form-item>
          </el-form>
          <el-col class="category">
            <span>选择商品分类：</span>
            <!-- 商品分类的级联选择框 -->
            <el-cascader
              v-model="selectCatId"
              :options="cateList"
              :props="cateProps"
              @change="handleChange"
            ></el-cascader>
          </el-col>
          <el-table
            :data="dataList"
            border
            @selection-change="selectionChangeHandle"
            style="width: 100%;">
            <el-table-column
              type="selection"
              header-align="center"
              align="center"
              width="50">
            </el-table-column>
            <el-table-column
              prop="attrGroupId"
              header-align="center"
              align="center"
              label="分组id">
            </el-table-column>
            <el-table-column
              prop="attrGroupName"
              header-align="center"
              align="center"
              label="组名">
            </el-table-column>
            <el-table-column
              prop="sort"
              header-align="center"
              align="center"
              label="排序">
            </el-table-column>
            <el-table-column
              prop="descript"
              header-align="center"
              align="center"
              label="描述">
            </el-table-column>
            <el-table-column
              prop="catelogId"
              header-align="center"
              align="center"
              label="所属分类">
            </el-table-column>
            <el-table-column
              fixed="right"
              header-align="center"
              align="center"
              width="280"
              label="操作">
              <template slot-scope="scope">
                <el-button type="success" icon="el-icon-setting" size="mini" @click="relationHandle(scope.row)">关联</el-button>
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="addOrUpdateHandle(scope.row.attrGroupId,scope.row)">修改</el-button>
                <el-button type="danger" size="mini" icon="el-icon-delete" @click="deleteHandle(scope.row.attrGroupId)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            @size-change="sizeChangeHandle"
            @current-change="currentChangeHandle"
            :current-page="pageIndex"
            :page-sizes="[5, 10, 15, 20]"
            :page-size="pageSize"
            :total="totalPage"
            layout="total, sizes, prev, pager, next, jumper">
          </el-pagination>
          <!-- 弹窗, 新增 / 修改 -->
          <GroupAddUpdate v-if="addOrUpdateVisible"  @updatedata="getAttrList" ref="addOrUpdate"></GroupAddUpdate>
        </div>
        </el-col>
      </el-row>
    </el-card>
    
    <!-- 关联弹框 -->
    <el-dialog
     
      :close-on-click-modal="false"
      :visible.sync="dialogTableVisible">
      <el-button type="primary" @click="addRelation()" >新增关联</el-button>
       <el-table :data="brandCategoryList" highlight-current-row  border>
        <el-table-column
        property="attrId"
         label="属性id"
          width="100">
        </el-table-column>
        <el-table-column
          property="attrName"
          label="属性名"
          width="150">
        </el-table-column>
        <el-table-column
          property="valueSelect"
          label="可选值">
        </el-table-column>
        
        <el-table-column
        fixed="right"
        header-align="center"
        align="center"
        width="100"
        label="操作">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="deleteBrandHandle(scope.row)">删除</el-button>
        </template>
      </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogTableVisible = false">关闭</el-button>
      </span>
    </el-dialog>
     <!-- 新增关联弹框 -->
    <el-dialog
      title="提示"
      :visible.sync="centerDialogVisible"
      width="50%"
      center>
      <el-form :inline="true" :model="attrForm" @keyup.enter.native="addRelation()">
        <el-form-item>
          <el-input v-model="attrForm.key" placeholder="参数名" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="addRelation()">查询</el-button>
        </el-form-item>
      </el-form>
      <el-table :data="attrCategoryList" highlight-current-row  border  @selection-change="handleSelectionChange">
         <el-table-column
          type="selection"
          width="55">
        </el-table-column>
        <el-table-column
          property="attrId"
          label="属性id"
          width="120">
        </el-table-column>
        <el-table-column
          property="attrName"
          label="属性名"
          width="180">
        </el-table-column>
        <el-table-column
          property="valueSelect"
          label="可选值列表">
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="centerDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="newAddRelation">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import GroupAddUpdate from './components/GroupAddUpdate'
export default {
  name: "Attrs",
  data() {
    return {
       // 商品分类列表
      cateList: [],
      //   级联选择框的配置对象
      cateProps: {
        expandTrigger: 'hover',
        value:"catId",
          label:'catName',
          children:"children"
      },
      dataForm: {
          key: ''
        },
      dataList: [],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      // 批量删除的catId
      dataListSelections: [],
      // 单个删除的catId
      deleteCatId:[],
      // 当前关联的分组ID
      realtionId :'',
      // 当前关联的分组名
      realtionName :'',
      // 关联弹框
      dialogTableVisible:false,
      // 新增关联弹框
      centerDialogVisible:false,
      // 对话框提示信息
      title:'',
      // 对话框类型
      dialogType:"",
      addOrUpdateVisible:"false",
      dialogFormVisible: false,
      brandCategoryList:[],
      multipleSelection: [],
      attrForm:{
         key:''
      },
      attrCategoryList:[
      ],
      //  选中是分类ID
      selectCatId:[]
    };
  },
  components:{
    GroupAddUpdate
  },
  created() {
    this.getAttrList()
    this.getCateList()
  },
  computed:{
    // 当前选中的二级分类Id
    getSelectCatId () {
      if (this.selectCatId.length === 2) {
        return this.selectCatId[1]
      }
      if (this.selectCatId.length === 0) {
        return 0 
      }
      return null
    },
  },
  methods: {
    //   获取所有的商品分类列表
      async getCateList () {
        const {data:res} = await this.$http.get("/xuanmall/category/list/tree")
          if(res.code === 0){
          this.cateList = this.formatData(res.data)
          // console.log(this.cateList)
          }
      },
      // 格式化数据，递归将空的children置为undefined
      formatData(data) {
        for (var i = 0; i < data.length; i++) {
          if (data[i].children.length < 1) {
            data[i].children = undefined
          } else {
            this.formatData(data[i].children)
          }
        }
        return data
        },
        // 分类级联选择器的点击事件
        handleChange(){
          this.getAttrList()
        },
      // 每页数
      sizeChangeHandle (val) {
        this.pageSize = val
        this.pageIndex = 1
        this.getAttrList()
      },
      // 当前页
      currentChangeHandle (val) {
        this.pageIndex = val
        this.getAttrList()
      },
      // 多选
      selectionChangeHandle (val) {
        this.dataListSelections = val
      },
      // 查询属性
      async  getAttrList(){ 
        const {data:res} = await this.$http.get(`/xuanmall/attrgroup/list/${this.getSelectCatId}?page=${this.pageIndex}&limit=${this.pageSize}&key=${this.dataForm.key}`)
        // console.log(res)
        this.dataList = res.page.list
        this.totalPage = res.page.totalCount
      },
      // 新增 / 修改
      addOrUpdateHandle (id,data) {
        this.addOrUpdateVisible = true
        // this.$nextTick 作用是当这个弹框组件完全显示后才获取数据
        this.$nextTick(() => {
          this.$refs.addOrUpdate.init(id,data)
        })
      },
      // 点击关联
      relationHandle(row){
        console.log(row)
        this.realtionId  = row.attrGroupId
        this.realtionName = row.arrGroupName
        this.getRelationData()
        this.dialogTableVisible =true
      },
      // 获取关联弹框数据
      async  getRelationData(){
        const {data:res} = await this.$http.get(`/xuanmall/attrgroup/${this.realtionId}/attr/relation`)
        this.brandCategoryList = res.data
      },
      async  addRelation(){
        this.getAddRelation()
        this.centerDialogVisible =true
      },
      // 获取新增关联弹框数据
      async  getAddRelation(){
        const {data:res} = await this.$http.get(`/xuanmall/attrgroup/${this.realtionId}/noattr/relation`)
        // console.log(res)
        if(res.msg === 'success'){
          this.attrCategoryList = res.page.list
        }
      },
      // 
      async  newAddRelation(){
         var relationAtrrIds = this.multipleSelection.map(item => {
          return item.attrId
        });
        var relationArrs = []
          relationAtrrIds.forEach((item) =>{
            var relationArrObj = {
               attrId : item,
               attrGroupId :this.realtionId,
               attrGroupName: this.realtionName
            }
              relationArrs.push(relationArrObj)
          })
        // console.log(relationArrs)
        const {data:res}  = await this.$http.post("/xuanmall/attrgroup/attr/relation",relationArrs)
        // console.log(res)
        if(res.msg === 'success'){
          this. getRelationData()
          this.$message.success("添加成功")
          this.centerDialogVisible = false
        }
      },
      // 多选框改变事件
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
      // 删除
      deleteHandle (id) {
        var ids = id ? [id] : this.dataListSelections.map(item => {
          return item.attrGroupId
        })
        this.$confirm(`确定对[id=${ids.join(',')}]进行[${id ? '删除' : '批量删除'}]操作?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then( async() => {
          const {data:res} = await this.$http.delete("/xuanmall/attrgroup/delete",{data:ids})
          
          if(res.msg === 'success'){
            this.getAttrList()
            this.$message.success("删除成功")
          }
          else{
            this.$message.error("删除失败")
          }
          
        })
      },
      // 添加关联中的删除
      deleteBrandHandle(data){
        this.$confirm(`确定删除该关联?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then( async() => {
          console.log(data) 
          const {data:res} = await this.$http.post("/xuanmall/attrgroup/attr/relation/delete",[{
            attrId:data.attrId,
            attrGroupId: this.realtionId
          }])
          console.log(res)
          if(res.msg === 'success'){
            this. getRelationData()
            this.$message.success("删除成功")
          }
          
        })
      }
  },
};
</script>
<style lang="less" scoped>
.category{
  margin: 20px 0;
}
</style>
